//
//  UIDevice+Orientation.m
//  yuLink
//
//  Created by aiwoba on 2021/8/24.
//

#import "UIDevice+Orientation.h"

@implementation UIDevice (Orientation)

+(CGFloat)statusBarHeight{
    
//    float statusBarHeight = 0;
//      if (@available(iOS 13.0, *)) {
//          UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].windows.firstObject.windowScene.statusBarManager;
//          statusBarHeight = statusBarManager.statusBarFrame.size.height;
//      }
//      else {
//          statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
//      }
//    NSLog(@"statusBarHeight:%f",statusBarHeight);
    //    return statusBarHeight;
    
    if (@available(iOS 13.0, *)) {
            NSSet *set = [UIApplication sharedApplication].connectedScenes;
            UIWindowScene *windowScene = [set anyObject];
            UIWindow *window = windowScene.windows.firstObject;
            return window.safeAreaInsets.top;
        } else if (@available(iOS 11.0, *)) {
            UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
            return window.safeAreaInsets.top;
        }
        return 20;


    
}

+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    [[self currentDevice]beginGeneratingDeviceOrientationNotifications];
    if (@available(iOS 16.0, *)) {
        UIInterfaceOrientationMask mask;
        if (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
            mask = UIInterfaceOrientationMaskLandscapeRight;
        } else {
            mask = UIInterfaceOrientationMaskPortrait;
        }
        UIWindowScene *scene = (UIWindowScene *)[[[[UIApplication sharedApplication]connectedScenes] allObjects]firstObject];
        UIWindowSceneGeometryPreferencesIOS *preference = [[UIWindowSceneGeometryPreferencesIOS alloc]initWithInterfaceOrientations:mask];
        [scene requestGeometryUpdateWithPreferences:preference errorHandler:^(NSError * _Nonnull error) {
        }];
        [[NSNotificationCenter defaultCenter]postNotificationName:UIDeviceOrientationDidChangeNotification object:@(interfaceOrientation)];
    } else {
        // Fallback on earlier versions
        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
        
        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
        
        NSNumber *orientationTarget = [NSNumber numberWithInteger:interfaceOrientation];
        
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
        [UIViewController attemptRotationToDeviceOrientation];
    }
}

+(NSInteger)previewRotationWithOrientation:(UIDeviceOrientation)orientation{
    if (orientation == UIDeviceOrientationLandscapeLeft) {
        return 3;
    } else if (orientation == UIDeviceOrientationLandscapeRight) {
        return 3;
    }
    return 0;
}

@end
